// pages/customerService/customerService.js
import {
  baseURL
} from '../../utils/request';
let SocketTask = null;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    socketTaskId: null, //socketId 
    chatList: [],
    inputVal: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initWebSocket();
  },
  initWebSocket() {
    const token = wx.getStorageSync('userInfo').token;
    SocketTask = wx.connectSocket({
      url: 'ws://127.0.0.1：8080/chat?token=' + token,
      success: (res) => {
        console.log('WebSocket connected:', res);
      },
      fail: (err) => {
        console.error('WebSocket connection failed:', err);
        wx.showToast({
          title: '连接失败，请检查网络',
          icon: 'none'
        });
      }
    });

    SocketTask.onOpen(() => {
      console.log('WebSocket connection opened');
      this.bindSocketEvents();
    });

    SocketTask.onError((err) => {
      console.error('WebSocket error:', err);
      wx.showToast({
        title: '连接出错，请稍后再试',
        icon: 'none'
      });
    });

    SocketTask.onClose(() => {
      console.log('WebSocket closed');
      // 可能需要在这里实现重连逻辑
    });
  },
  bindSocketEvents() {
    SocketTask.onMessage(({
      data
    }) => {
      try {
        const message = JSON.parse(data); // 假设消息是以JSON格式发送的
        this.handleIncomingMessage(message);
      } catch (e) {
        console.error('Failed to parse incoming message:', e);
      }
    });

    SocketTask.onClose(() => {
      console.log('WebSocket closed');
      // 可能需要在这里实现重连逻辑
    });
  },
  handleIncomingMessage(message) {
    // 处理从服务器接收到的消息
    const chatItem = {
      id: message.id,
      chatData: message.content,
      url: message.url || "",
      name: message.senderName || "客服"
    };
    const newChatList = [...this.data.chatList, chatItem];
    this.setData({
      chatList: newChatList,
      toView: `item${(newChatList.length - 1)}`
    });
  },

  sendMessage(e) {
    const deptName = wx.getStorageSync('userInfo').deptName;
    const imageUrl = wx.getStorageSync('userInfo').imageUrl;
    const deptUrl = imageUrl ? `${baseURL}${imageUrl}` : "";
    const messageContent = e.detail.value.message;

    if (!messageContent.trim()) return; // 防止发送空消息

    const message = {
      id: 2,
      chatData: messageContent,
      url: deptUrl,
      name: deptName
    };

    SocketTask.send({
      data: JSON.stringify(message), // 发送JSON格式的消息
      success: () => {
        const newChatList = [...this.data.chatList, message];
        this.setData({
          chatList: newChatList,
          toView: `item${(newChatList.length - 1)}`,
          inputVal: ""
        });
      },
      fail: () => {
        wx.showToast({
          title: '发送失败，请重试',
          icon: 'none'
        });
      }
    });
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let chatData = wx.getStorageSync("chatData") || [];
    this.setData({
      chatList: chatData
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    //小程序后台存储聊天
    console.log("onhide")
    wx.setStorageSync('chatData', this.data.chatList || [])
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    //返回页面 存储聊天数据
    console.log("unload")
    wx.setStorageSync('chatData', this.data.chatList || []);
    SocketTask.close({
      code: 1000
    })
  },

})